package org.fatmansoft.teach.controllers.ViewController;

import org.fatmansoft.teach.Repository.ViewRepository.PracticeInfo.PracticeTypeRepository;
import org.fatmansoft.teach.Repository.ViewRepository.PracticeInfo.StudentPracticeRepository;
import org.fatmansoft.teach.Repository.ViewRepository.StudentRepository;
import org.fatmansoft.teach.entity.ViewEntity.PracticeInfo.PracticeType;
import org.fatmansoft.teach.entity.ViewEntity.PracticeInfo.StudentPractice;
import org.fatmansoft.teach.entity.ViewEntity.Student;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/practiceInfo")
public class StudentPracticeController {
    @Autowired
    StudentRepository studentRepository;

    @Autowired
    StudentPracticeRepository studentPracticeRepository;

    @Autowired
    PracticeTypeRepository practiceTypeRepository;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @PostMapping("/getInfo")
    public DataResponse getInfo(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        int currentPage = 1;  //分页页码
        String RequestCurPage = Utils.parseRequest(request, "currentPage", map);  //获取解析的数据
        if (RequestCurPage != null & Utils.checkNum(RequestCurPage)) {  //要求数据不为空，且为纯数字
            currentPage = Integer.parseInt(RequestCurPage);
        }

        Integer studentNum = -1;  //学号
        String RequestStuNum = Utils.parseRequest(request, "studentNum", map);  //获取解析的数据
        if (RequestStuNum != null) {  //要求数据不为空
            studentNum = Integer.parseInt(RequestStuNum);
        }

        List<StudentPractice> studentPracticeList;  //创建学生列表，用于返回前端
        if (RequestStuNum != null) {  //按照学号查询
            studentPracticeList = studentPracticeRepository.findStudentPracticesByStudentId(studentNum);
        } else {  //不按照学号查询
            studentPracticeList = studentPracticeRepository.findAll(PageRequest.of(currentPage - 1, 5)).toList();
        }

        List<Student> studentList = studentRepository.findAll().subList(0, studentRepository.findAll().size());

        map.put("tableData", studentPracticeList);
        map.put("studentList", studentList);  //传递studentList，从而生成学生id的选择框
        map.put("total", studentPracticeRepository.findAll().size());

        return new DataResponse("0", map);
    }

    @PostMapping("/deleteInfo")
    public DataResponse delete(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        String deleteId = Utils.parseRequest(request, "deleteId", map);
        //System.out.println(deleteId);
        if (Utils.checkNum(deleteId)) {
            studentPracticeRepository.deleteById(Integer.parseInt(deleteId));
        }

        return new DataResponse("0", map);
    }

    @PostMapping("/updateAndCreateInfo")
    public DataResponse updateAndCreate(@Valid @RequestBody DataRequest request) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        String code;
//        从前端获取formData转化为Map
        Map formData = (Map) request.getData().get("formData");

        StudentPractice studentPractice = new StudentPractice();  //学生实践对象
        Student theStudent = new Student();  //学生对象

        if (formData.get("id") != null) studentPractice.setId(Integer.parseInt(formData.get("id").toString()));
        else if(studentPracticeRepository.findAll().size()==0){  //如果没有传入id->查找数据库
//            数据库没有记录->赋值为1
            studentPractice.setId(1);
        }else{
//            有记录->赋值为最后一条记录的id+1
            int lastRecord = studentPracticeRepository.findAll().size() - 1;
            int lastId = studentPracticeRepository.findAll().get(lastRecord).getId();
            studentPractice.setId(lastId + 1);
        }
        if (formData.get("studentId") != null) {  //获取学生ID
            theStudent.setId(Integer.parseInt(formData.get("studentId").toString()));
            studentPractice.setStudent(theStudent);
        }
        if (formData.get(" studentName") != null) {  //获取学生姓名
            theStudent.setStudentName(formData.get(" studentName").toString());
            studentPractice.setStudent(theStudent);
        }
        if (formData.get("practiceTypeId") != null) {  //获取实践类型的方法
            PracticeType practiceType = new PracticeType();
            if (practiceTypeRepository.findById((int) Long.parseLong(formData.get("practiceTypeId").toString())).isPresent()) {
                practiceType = practiceTypeRepository.findById((int) Long.parseLong(formData.get("practiceTypeId").toString())).get();
            }
            studentPractice.setPracticeType(practiceType);
        }
        if (formData.get("practiceName") != null)
            studentPractice.setPracticeName(formData.get("practiceName").toString());
        if (formData.get("practiceBeginDate") != null)
            studentPractice.setPracticeBeginDate(sdf.parse(formData.get("practiceBeginDate").toString() + " 00:00:00"));  //获取活动日期
        if (formData.get("practiceEndDate") != null)
            studentPractice.setPracticeEndDate(sdf.parse(formData.get("practiceEndDate").toString() + " 00:00:00"));  //获取活动日期
        if (formData.get("practiceDescription") != null)
            studentPractice.setPracticeDescription(formData.get("practiceDescription").toString());
        if (formData.get("practiceCost") != null)
            studentPractice.setPracticeCost(Double.valueOf(formData.get("practiceCost").toString()));


//        判断当前元组是否已经存在（根据ID是否存在)
        if (studentPracticeRepository.findById(studentPractice.getId()).isPresent()) {  //查看id是否已经存在
            code = "0"; //表示更新
        } else {
            code = "1"; //表示新增
        }

        studentPracticeRepository.save(studentPractice);  //更新/保存的数据

        return new DataResponse(code, map);
    }
}
